package com.heiyu.controller;

import com.google.common.collect.Maps;
import com.heiyu.controller.request.ArticleListRequest;
import com.heiyu.controller.request.BaseRequest;
import com.heiyu.controller.response.BaseResponse;
import com.heiyu.dao.ArticleInfoMapper;
import com.heiyu.dao.ClientPushInfoMapper;
import com.heiyu.dao.UserPushInfoMapper;
import com.heiyu.entity.ArticleInfo;
import com.heiyu.entity.BigAuthorFollow;
import com.heiyu.entity.ClientPushInfo;
import com.heiyu.entity.UserPushInfo;
import com.heiyu.utils.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Api
@RestController
@RequestMapping("article")
public class ArticleController extends AdminBaseController {

    @Autowired
    private ArticleInfoMapper articleInfoMapper;
    @Autowired
    private ClientPushInfoMapper clientPushInfoMapper;
    @Autowired
    private UserPushInfoMapper userPushInfoMapper;

    @ApiOperation(value = "list",notes = "文章列表")
    @RequestMapping(value = "list",method = RequestMethod.GET)
    public BaseResponse list(@ModelAttribute ArticleListRequest request){
        BaseResponse response = new BaseResponse();
        Map<String,Object> param = Maps.newHashMap();
        if(!StringUtils.isEmpty(request.getSingleKey())){
            param.put("title",request.getSingleKey());
        }
        if(request.getItemId()!=null && request.getItemId() != 0){
            param.put("itemId",request.getItemId());
        }
        param = PageHelper.page(articleInfoMapper,param,request.getPageIndex(),request.getPageSize());
        response.success();
        response.setData(param);
        return response;
    }

    @ApiOperation(value = "get",notes = "文章详情")
    @RequestMapping(value = "get",method = RequestMethod.GET)
    public BaseResponse get(@ModelAttribute BaseRequest request){
        BaseResponse response = new BaseResponse();
        ArticleInfo articleInfo = this.articleInfoMapper.selectPrimary(Long.valueOf(request.getTargetId()));
        if(articleInfo == null){
            response.error("信息不存在");
        }else{
            response.success();
            response.setData(articleInfo);
        }
        return response;
    }

    @ApiOperation(value = "update",notes = "更新文章信息")
    @RequestMapping(value = "update",method = RequestMethod.POST)
    public BaseResponse update(@ModelAttribute ArticleInfo articleInfo){
        BaseResponse response = new BaseResponse();
        ArticleInfo info = this.articleInfoMapper.selectPrimary(articleInfo.getId());
        if(info == null){
            response.error("信息不存在");
        }else{
            this.articleInfoMapper.updateById(articleInfo);
            response.success();
        }
        return response;
    }


    @ApiOperation(value = "put",notes = "新增文章信息")
    @RequestMapping(value = "put",method = RequestMethod.POST)
    public BaseResponse put(@ModelAttribute ArticleInfo articleInfo){
        BaseResponse response = new BaseResponse();
        if(StringUtils.isEmpty(articleInfo.getContent())||StringUtils.isEmpty(articleInfo.getImgUrl())||StringUtils.isEmpty(articleInfo.getTitle())||articleInfo.getUserId()==null||articleInfo.getUserId() == 0){
            response.error("参数错误");
            return response;
        }
        if(articleInfo.getItemId() == null || articleInfo.getItemId() == 0){
            articleInfo.setItemId(3l);
        }
        articleInfo.setCreatedTime(new Date());
        articleInfo.setModifyTime(new Date());
        articleInfo.setIsDeleted("0");
        articleInfo.setRank(49);
        articleInfo.setArticleType(articleInfo.getItemId()==2?1:2);
        articleInfo.setShotDesc(articleInfo.getTitle());
        articleInfo.setShareTimes(0);
        if(articleInfo.getItemId()==2){
            Pattern p_html = Pattern.compile("<[^>]+>", Pattern.CASE_INSENSITIVE);
            Matcher m_html = p_html.matcher(articleInfo.getContent());
            String content  = m_html.replaceAll("");
            articleInfo.setContent(content);
        }
        this.articleInfoMapper.insert(articleInfo);
        response.success();
        return response;
    }

    @ApiOperation(value = "del",notes = "删除文章")
    @RequestMapping(value = "del",method = RequestMethod.POST)
    public BaseResponse del(@RequestBody BaseRequest request){
        BaseResponse response = new BaseResponse();
        ArticleInfo info = this.articleInfoMapper.selectPrimary(Long.valueOf(request.getTargetId()));
        if(info == null){
            response.error("信息不存在");
        }else{
            this.articleInfoMapper.delete(info.getId());
            response.success();
        }
        return response;
    }

    @ApiOperation(value = "rank/update",notes = "置顶文章")
    @RequestMapping(value = "rank/update",method = RequestMethod.POST)
    public BaseResponse rankUpdate(@ModelAttribute BaseRequest request){
        BaseResponse response = new BaseResponse();
        ArticleInfo articleInfo = this.articleInfoMapper.selectPrimary(Long.valueOf(request.getTargetId()));
        if(articleInfo== null){
            response.error("文章信息不存在");
        }else{
            articleInfo = new ArticleInfo();
            articleInfo.setRank(100);
            articleInfo.setIndex(0);
            articleInfo.setOffset(20);
            List<ArticleInfo> list = this.articleInfoMapper.selectList(articleInfo);
            if(!CollectionUtils.isEmpty(list)){
                for(ArticleInfo info:list){
                    info.setRank(99);
                    this.articleInfoMapper.updateById(info);
                }
            }
            articleInfo.setId(Long.valueOf(request.getTargetId()));
            this.articleInfoMapper.updateById(articleInfo);
            response.success();
        }

        return response;
    }

    @ApiOperation(value = "daka/down",notes = "下架大卡文章")
    @RequestMapping(value = "daka/down",method = RequestMethod.POST)
    public BaseResponse dakaDown(@ModelAttribute BaseRequest request){
        BaseResponse response = new BaseResponse();
        ArticleInfo articleInfo = this.articleInfoMapper.selectPrimary(Long.valueOf(request.getTargetId()));
        if(articleInfo== null){
            response.error("文章信息不存在");
        }else{
            if(articleInfo.getArticleType().equals("1")){
                articleInfo.setItemId(2l);
            }else{
                articleInfo.setItemId(3l);
            }
            this.articleInfoMapper.updateById(articleInfo);
            response.success();
        }
        return response;
    }


    @ApiOperation(value = "rank/down/update",notes = "取消文章置顶")
    @RequestMapping(value = "rank/down/update",method = RequestMethod.POST)
    public BaseResponse rankDownUpdate(@ModelAttribute BaseRequest request){
        BaseResponse response = new BaseResponse();
        ArticleInfo info = this.articleInfoMapper.selectPrimary(Long.valueOf(request.getTargetId()));
        if(info == null){
            response.error("信息不存在");
        }else{
            info.setRank(50);
            this.articleInfoMapper.updateById(info);
            response.success();
        }
        return response;
    }

    @PostMapping("author/update")
    public BaseResponse authorUpdate(@ModelAttribute ArticleInfo articleInfo){
        BaseResponse response = new BaseResponse();
        response.success();
        articleInfo.setRank(50);
        this.articleInfoMapper.updateById(articleInfo);
        //获取关注该大咖的用户
        List<ClientPushInfo> list = this.clientPushInfoMapper.listNotCloseAuthor(articleInfo.getUserId());
        if(!CollectionUtils.isEmpty(list)){
            StringBuilder iosUsers = new StringBuilder();
            StringBuilder androidUsers = new StringBuilder();
            for(ClientPushInfo pushInfo:list){
                if(pushInfo.getClientType().equals("1")){
                    iosUsers.append(pushInfo.getPushId()).append(",");
                }else{
                    androidUsers.append(pushInfo.getPushId()).append(",");
                }
            }
            Pattern p_html = Pattern.compile("<[^>]+>", Pattern.CASE_INSENSITIVE);
            Matcher m_html = p_html.matcher(articleInfo.getContent());
            String content  = m_html.replaceAll("");
            UserPushInfo userPushInfo = new UserPushInfo();
            userPushInfo.setTitle(articleInfo.getTitle());
            userPushInfo.setContent(content.substring(0,content.length()>=30?30:content.length())+"...");
            userPushInfo.setStatus("1");
            userPushInfo.setCreatedTime(new Date());
            userPushInfo.setModifyTime(new Date());
            userPushInfo.setIsDeleted("0");
            userPushInfo.setSendTime(new Date());
            if(articleInfo.getArticleType()==1)
                userPushInfo.setExt("{\"schema\":\"schema://heiyu.com/author?authorId="+articleInfo.getUserId()+"\"}");
            else
                userPushInfo.setExt("{\"schema\":\"schema://heiyu.com/information/detail?articleId="+articleInfo.getId()+"\"}");
            if(iosUsers.length()>0){
                userPushInfo.setClientType("1");
                userPushInfo.setPushIds(iosUsers.substring(0,iosUsers.length()-1));
                this.userPushInfoMapper.insert(userPushInfo);
            }
            if(androidUsers.length()>0){
                userPushInfo.setClientType("2");
                userPushInfo.setPushIds(androidUsers.substring(0,androidUsers.length()-1));
                userPushInfo.setId(null);
                this.userPushInfoMapper.insert(userPushInfo);
            }
        }
        return response;
    }

    @ApiOperation(value = "publish/update",notes = "发布文章")
    @RequestMapping(value = "publish/update",method = RequestMethod.POST)
    public BaseResponse publish(@ModelAttribute BaseRequest request){
        BaseResponse response = new BaseResponse();
        ArticleInfo info = this.articleInfoMapper.selectPrimary(Long.valueOf(request.getTargetId()));
        if(info == null){
            response.error("信息不存在");
        }else{
            info.setRank(50);
            this.articleInfoMapper.updateById(info);
            response.success();
        }
        return response;
    }

    @ApiOperation(value = "publish/down/update",notes = "下架文章")
    @RequestMapping(value = "publish/down/update",method = RequestMethod.POST)
    public BaseResponse downPublish(@ModelAttribute BaseRequest request){
        BaseResponse response = new BaseResponse();
        ArticleInfo info = this.articleInfoMapper.selectPrimary(Long.valueOf(request.getTargetId()));
        if(info == null){
            response.error("信息不存在");
        }else{
            info.setRank(49);
            this.articleInfoMapper.updateById(info);
            response.success();
        }
        return response;
    }
}
